package com.aabbc.validation.controller;

import com.aabbc.validation.entity.User;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validator;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.time.Instant;
import java.util.Set;

/**
 * ValidationController
 *
 * @author: <a href="mailto:chenfenghai@oristartech.com">chenfenghai</a>
 * @version: 1.0
 * @date: 2019-11-29 17:51
 */
@Validated
@RestController
public class ValidationController {

    @Autowired
    private Validator validator;

    @GetMapping("/test")
    public String test(){
        return "ValidationController.test" + Instant.now().toEpochMilli();
    }

    @GetMapping("/t1")
    public long test1(@Range(min = 1, max = 9, message = "年级只能从1-9")
                     @RequestParam(name = "grade", required = true)
                             int grade,
                     @Min(value = 1, message = "班级最小只能1")
                     @Max(value = 99, message = "班级最大只能99")
                     @RequestParam(name = "classroom", required = true)
                             int classroom){
        return Instant.now().toEpochMilli();
    }

    @PostMapping("/t2")
    public long test2(@RequestBody @Valid User user){
        return Instant.now().toEpochMilli();
    }

    @PostMapping("/t3")
    public String test3(@RequestBody User user){
        Set<ConstraintViolation<User>> result = validator.validate(user);
        if(!result.isEmpty()){
            return result.iterator().next().getMessage();
        }
        return String.valueOf(Instant.now().toEpochMilli());
    }
}
